import {
    defineStore
} from 'pinia';
import {
    computed,
    ref,
} from 'vue';

export const useCounterStore = defineStore('car', () => {
    // 购物车数组
    let cardList = ref([]);
    // 总价
    let total = computed(() => {
        return cardList.value.reduce((prev, next) => {
            return prev += next.money * next.shopNum;
        }, 0);
    })
    //累计
    let count = computed(() => {
        return cardList.value.reduce((prev, next) => {
            return prev += next.shopNum;
        }, 0);
    })
    //购物车步进器 （个数，修改的节点）
    function setList(value, item) {
        let index = cardList.value.findIndex((find) => find._id == item._id);
        if (value == 1 && index == -1) {
            cardList.value.push({
                ...item,
                shopNum: 1
            })
        } else if (value == 0) {
            cardList.value[index].shopNum = 0;
            cardList.value.splice(index, 1);
        } else {
            cardList.value[index].shopNum = value;
        }
    }
    //清空购物车
    function clearCar() {
        cardList.value.length = 0;
    }
    //统计优惠价格
    let freeCount = computed(() => {
        return cardList.value.reduce((prev, next) => {
            let preMoney = next.deMoney || next.money;
            return prev += next.shopNum * (preMoney - next.money);
        }, 0);
    })
    return {
        cardList,
        total,
        setList,
        count,
        clearCar,
        freeCount
    }
}, {
    persist: true
});